package autohome.wz.job;

import autohome.wz.lib.AutoHomeNewsHelper;
import autohome.wz.lib.Common;
import autohome.wz.lib.HttpRequest;
import autohome.wz.model.AutoHomeNews;
import autohome.wz.model.YouChuang.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 优创+ 文章列表：
 * http://youchuang.api.autohome.com.cn/InfoService.svc/GetAllList?_appid=cms&start=1&count=10&orderType=
 * 优创+ 文章详情
 * http://youchuang.api.autohome.com.cn/InfoService.svc/GetInfoDetail?_appid=cms&infoId=89073&fromWriteDb=False
 *
 * 车家号 文章类表
 * http://chejiahao.api.lq.autohome.com.cn/InfoService.svc/GetAllList?_appid=cms&start=1&count=100&orderType=
 * 车家号文章详情
 * http://chejiahao.api.lq.autohome.com.cn/InfoService.svc/GetInfoDetail?_appid=cms&infoId=2009213&fromWriteDb=False
 *
 *
 *
 * Created with Administrator
 * DATE:2016/12/22
 * Time:17:29
 */
public class YouChuangJob implements Job {

    public static void main(String[] arg0) {
        YouChuangJob.invoke();
    }

    private static Logger logger = Logger.getLogger(YouChuangJob.class);

    /**
     * 获取抓取数据天数。当为0时抓取所有数据。
     */
    private static int InDay = 2;

    public void execute(JobExecutionContext arg0) {
        invoke();
    }

    public static void invoke() {
        int PageStart = 1;
        int pageSize = 100;
        long totalCount;
        do {
            totalCount = GetData(PageStart, pageSize);
            PageStart += pageSize;
        } while (PageStart <= totalCount);
    }

    private static long GetData(int start, int size) {
        long totalNum = 0;
        int bizType = 12;
        String url = "http://youchuang.api.autohome.com.cn/InfoService.svc/GetAllList";
        String param = MessageFormat.format("_appid={0}&start={1}&count={2}&orderType={3}", "cms", start, size, "");
        String result = HttpRequest.sendGet(url, param);
        if (!result.equals("")) {
            Gson gson = new Gson();
            YouChuangApiResult<YouChuangResult> apiResult;
            try {
                apiResult = gson.fromJson(result, new TypeToken<YouChuangApiResult<YouChuangResult>>() {
                }.getType());
                if (apiResult != null) {
                    //文章总数
                    totalNum = apiResult.getResult().getTotalCount();
                    List<YouChuangArticle> list = apiResult.getResult().getItems();
                    //验证本批数据是否需要抓取
                    if (!checkSpiderDate(list)) {
                        //若没有需要抓取的数据，则返回数量0
                        totalNum = 0;
                    } else {
                        if (list != null && list.size() > 0) {
                            for (YouChuangArticle article : list) {
                                long articleId = article.getInfoId();
                                //信息类型1文章、2文图、3视频、4音频
                                int infotype = article.getInfoType();
                                List array = Arrays.asList(1, 2);
                                if (articleId > 0 && array.contains(infotype)) {
                                    YouChuangDetail detail = getYouChuangDetail(articleId);
                                    if (detail != null && detail.getArticle() != null && detail.getArticle().getContent() != null) {
                                        AutoHomeNews model = new AutoHomeNews();
                                        model.setBiz_id(article.getInfoId());
                                        model.setBiz_type(bizType);
                                        String title = article.getTitle();
                                        model.setTitle(title);
                                        model.setAuthor(article.getAuthor().getNickName());
                                        model.setCms_content_class("");
                                        model.setCms_series_id("");
                                        if (article.getTags().size() > 0) {
                                            ArrayList<String> listTags = new ArrayList<String>();
                                            for (TagDto tag : article.getTags()) {
                                                listTags.add(tag.getTagName());
                                            }
                                            model.setCms_tags(Common.listToString(listTags, ','));
                                        }
                                        model.setContent(detail.getArticle().getContent());
                                        model.setImg_url(Common.getAutoHomeImageSrc(detail.getArticle().getCoverImage()));
                                        model.setGraphic_img_list2("");
                                        model.setIndex_detail(article.getDescription());
                                        model.setImg_url2("");
                                        model.setPublish_time(Common.GetSqlTimeSpan2(article.getPublishTime()));
                                        int addResult = AutoHomeNewsHelper.Add(model);
                                        if (addResult > 0) {
                                            logger.error(article.getTitle() + "入库成功");
                                        } else {
                                            logger.error(article.getTitle() + "入库失败");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("YouChuangJob-GetData:" + e.getMessage());
            }
        }
        return totalNum;
    }

    private static boolean checkSpiderDate(List<YouChuangArticle> list) {
        boolean result = false;
        if (list != null && list.size() > 0) {
            for (YouChuangArticle article : list) {
                try {
                    Date d1 = Common.getSpiderDate(InDay);
                    Date d2 = Common.GetSqlTimeSpan2(article.getPublishTime());
                    if (d2.compareTo(d1) > 0) {
                        result = true;
                        break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Common.showMessage(e.getMessage());
                    break;
                }
            }
        }
        return result;
    }

    /**
     * 获取说客文章详情内容
     *
     * @param articleId 文章ID
     * @return 说客文章内容详情
     */
    private static YouChuangDetail getYouChuangDetail(long articleId) {
        String baseDetailUrl = "http://youchuang.api.autohome.com.cn/InfoService.svc/GetInfoDetail";
        String baseDetailParam = MessageFormat.format("_appid=cms&infoId={0}&fromWriteDb=False", Long.toString(articleId));
        YouChuangApiResult<YouChuangDetail> result;
        if (articleId > 0) {
            String apiResult = HttpRequest.sendGet(baseDetailUrl, baseDetailParam);
            if (!apiResult.equals("") && apiResult.length() > 0) {
                Gson gson = new Gson();
                try {
                    result = gson.fromJson(apiResult, new TypeToken<YouChuangApiResult<YouChuangDetail>>() {
                    }.getType());
                    if (result != null) {
                        return result.getResult();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("GetYouChuangDetail:" + e.getMessage());
                }
            }
        }
        return null;
    }
}
